package process

import (
	"baidu/apiSpeech"
	"baidu/config"
	"baidu/file"
	"baidu/params"
	"fmt"
	"io/ioutil"
	"strconv"
	"time"
)

// 读取文件内容
func ReadContent(textFiles []string, cContent chan config.FileContent) {
	for _, storyFileName := range textFiles {
		// 并发数下控制 文件读取的个数
		if config.Concurrent.Get() > params.ConcurrentMax*2 {
			time.Sleep(1 * time.Second)
			continue
		}

		go func(cContent chan config.FileContent, storyFileName string) {
			//  按长度切割文本长度
			var contentArr []string = file.Read(params.BasePath, storyFileName, params.LimitLen)
			config.ContentCount += len(contentArr)

			fmt.Printf("内容读取完成:%s 完成时间%d\n", storyFileName, time.Now().Unix()-params.StartTime)

			for i, content := range contentArr {
				cContent <- config.FileContent{FileName: storyFileName, Content: content, I: i}
			}

		}(cContent, storyFileName)
	}
}

// 转语音
func ToAudio(cContent chan config.FileContent, cWrite chan config.FileContent) {
	var FileContent config.FileContent = config.FileContent{}
	for {
		// 控制并发数
		if config.Concurrent.Get() >= params.ConcurrentMax {
			time.Sleep(1 * time.Second)
			continue
		}

		select {
		case FileContent = <-cContent:
			config.Concurrent.Increment()
			// 转语音
			go func(FileContent config.FileContent) {
				fmt.Printf("语音转换开始:%s %d 完成时间%d\n", FileContent.FileName, FileContent.I, time.Now().Unix()-params.StartTime)

				var audioContent string = apiSpeech.Synthesis(FileContent.Content, "zh", "1", map[string]interface{}{
					"vol": "5",
					"per": params.Per,
				})

				fmt.Printf("语音转换完成:%s %d 完成时间%d\n", FileContent.FileName, FileContent.I, time.Now().Unix()-params.StartTime)

				config.Concurrent.Decrement()
				cWrite <- config.FileContent{FileName: FileContent.FileName, Content: audioContent, I: FileContent.I}

			}(FileContent)
		}
	}
}

// 写入文件
func WriteFile(cWrite chan config.FileContent, cEnd chan int) {
	var writeContent config.FileContent
	for {
		select {
		case writeContent = <-cWrite:
			// 写入mp3文件
			go func(writeContent config.FileContent, cEnd chan int) {
				err := ioutil.WriteFile(params.BasePath+"/"+writeContent.FileName+"_"+strconv.Itoa(writeContent.I)+".mp3", []byte(writeContent.Content), 0777)
				if err != nil {
					panic(err)
				}

				fmt.Printf("文件写入:%s %d 完成时间%d\n", writeContent.FileName, writeContent.I, time.Now().Unix()-params.StartTime)

				cEnd <- 1
			}(writeContent, cEnd)
		}
	}
}

func ListenProcess(cEnd chan int) {
	var completeNumber int = 0
	for {
		select {
		case <-cEnd:
			completeNumber++
			fmt.Printf("%d %d\n", config.ContentCount, completeNumber)
			if config.ContentCount == completeNumber {
				fmt.Printf("已完成：%d 完成时间%d\n", completeNumber, time.Now().Unix()-params.StartTime)

				fmt.Printf("%s\n", "已全部完成，30秒种后推出程序")
				time.Sleep(30 * time.Second)
				return
			}
		}
	}
}
